package ua.edu.nuos.tees.jdmmon.dao.serial;

import gnu.io.*;
import ua.edu.nuos.tees.jdmmon.dao.exceptions.ComPortInUseException;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author Timur Yarosh
 *         Date: 06.06.13
 *         Time: 22:04
 */
public class RxtxWrapper {
    public static void send(
            byte[] bytes,
            String portName,
            int speed,
            int databits,
            int stopbits,
            int parity
    ) throws NoSuchPortException, ComPortInUseException, PortInUseException, UnsupportedCommOperationException, IOException {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        if (portIdentifier.isCurrentlyOwned()) {
            throw new ComPortInUseException();
        }
        CommPort commPort = portIdentifier.open("RxtxWrapper", 2000);
        if (commPort instanceof SerialPort) {
            SerialPort serialPort = (SerialPort) commPort;
            serialPort.setSerialPortParams(speed, databits, stopbits, parity);
            OutputStream outputStream = serialPort.getOutputStream();
            outputStream.write(bytes);
        }
    }

    /**
     * @param bytes number of bytes to receive
     * @return
     */
    public static byte[] receive(
            int bytes,
            String portName,
            int speed,
            int databits,
            int stopbits,
            int parity
    ) throws NoSuchPortException, ComPortInUseException, PortInUseException, UnsupportedCommOperationException, IOException {
        byte[] buffer = new byte[bytes];
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        if (portIdentifier.isCurrentlyOwned()) {
            throw new ComPortInUseException();
        }
        CommPort commPort = portIdentifier.open("RxtxWrapper", 2000);
        if (commPort instanceof SerialPort) {
            SerialPort serialPort = (SerialPort) commPort;
            serialPort.setSerialPortParams(speed, databits, stopbits, parity);
            InputStream inputStream = serialPort.getInputStream();
            inputStream.read(buffer);
        }
        return buffer;
    }
}
